<?php


namespace App\Admin\Controllers;

use App\Admin\Forms\Stock\ImportRecord;
use App\Admin\Services\GoodService;
use App\Admin\Services\StockService;
use App\Http\Controllers\Controller;
use Box\Spout\Common\Exception\IOException;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Box\Spout\Writer\Exception\WriterNotOpenedException;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;


class StockController extends Controller
{
    public function index(Content $content)
    {
        Admin::js(('js/datatable-responsive/datatables.responsive.min.js'));
        Admin::css('css/jquery.dataTables.min.css');
        Admin::js('js/datatables/jquery.dataTables.min.js');
        Admin::disablePjax();

        $content->view('Stock.index',['is_admin' => Admin::user()->inRoles(['susan', 'administrator'])]);
        return $content;
    }

    /**
     * 进出记录
     *
     * @param Content $content
     * @return Content
     */
    public function record(Content $content)
    {
        Admin::css('css/jquery.dataTables.min.css');
        $content->view('Stock.record');
        Admin::js(('js/datatable-responsive/datatables.responsive.min.js'));
        Admin::js('js/datatables/jquery.dataTables.min.js');
        Admin::disablePjax();
        return $content;
    }

    /**
     * @desc 获取进出记录
     *
     * @param Request $request
     * @param StockService $stockService
     *
     * @return \Illuminate\Http\JsonResponse
     *
     * @author: 梅杰[meijie3169@dingtalk.com] at 2020-03-18 16:33:37
     */
    public function getRecord(Request $request , StockService $stockService)
    {
        $data = $stockService->getRecordsList($request->input('columns'),
            $request->input('order'),
            $request->input('length', 10),
            $request->input('start', 0)
        );

        return datatableResponse($request->input('draw'), $data['total'], $data['data']);
    }

    /**
     * 库存导出
     *
     * @param GoodService $goodService
     * @throws IOException
     * @throws WriterNotOpenedException
     * @author: 梅杰 2020/2/20 18:03
     */
    public function doExport(GoodService $goodService)
    {
        $cells = [
            WriterEntityFactory::createCell('ASIN'),
            WriterEntityFactory::createCell('USSKU'),
            WriterEntityFactory::createCell('CASKU'),
            WriterEntityFactory::createCell('UKSKU'),
            WriterEntityFactory::createCell('JPSKU'),
            WriterEntityFactory::createCell('WEB_SKU'),
            WriterEntityFactory::createCell('USFNSKU'),
            WriterEntityFactory::createCell('STOCK'),
            WriterEntityFactory::createCell('KF_NOTE'),
        ];
        if (Admin::user()->inRoles(['susan', 'administrator'])) {
            $cells[] = WriterEntityFactory::createCell('ADMIN_NOTE');
            $cells[] = WriterEntityFactory::createCell('货号');
            $cells[] = WriterEntityFactory::createCell('颜色');
            $cells[] = WriterEntityFactory::createCell('供应商');
        }
        $fileName = "stock" . date('YmdHis') . ".csv";
        $writer = WriterEntityFactory::createCSVWriter()->openToBrowser($fileName);
        $singleRow = WriterEntityFactory::createRow($cells);
        $writer->addRow($singleRow);
        $data = $goodService::getStockExportData();
        foreach ($data as $datum) {
            if (!($datum->totalStock->stock ?? 0)) {
                continue;
            }

            $values = [
                WriterEntityFactory::createCell($datum->amazonGood->asin),
                WriterEntityFactory::createCell($datum->amazonGood->sku),
                WriterEntityFactory::createCell($datum->casku),
                WriterEntityFactory::createCell($datum->uksku),
                WriterEntityFactory::createCell($datum->jpsku),
                WriterEntityFactory::createCell($datum->web_sku),
                WriterEntityFactory::createCell($datum->amazonGood->fnsku),
                WriterEntityFactory::createCell($datum->totalStock->stock),
                WriterEntityFactory::createCell($datum->lastCustomNote->content ?? ''),

            ];
            if (Admin::user()->inRoles(['susan', 'administrator'])) {
                $values[] = WriterEntityFactory::createCell($datum->lastAdminNote->content ?? '');
                $values[] = WriterEntityFactory::createCell($datum->number);
                $values[] = WriterEntityFactory::createCell($datum->color);
                $values[] = WriterEntityFactory::createCell($datum->supplier->name ?? '');
            }
            $singleRow = WriterEntityFactory::createRow($values);
            $writer->addRow($singleRow);
        }
        $writer->close();
    }

    /**
     * 库存导出
     *
     * @param Content $content
     * @return Content
     */
    public function export(Content $content)
    {
        $prefix = config('admin.route.prefix');
        Admin::script("$(function(){
            var a = document.createElement('a');
            a.href = $prefix '/stock/doExport';
            a.target = '_blank';
            a.click();
            $(a).remove();
            $('body').append(a);    // 修复firefox中无法触发click
        })");

        return $content->withSuccess('操作成功', '正在导出中');
    }

    /**
     * 库存进出记录导入
     *
     * @param Content $content
     * @return Content
     */
    public function recordImport(Content $content)
    {
        return $content->body(new ImportRecord());
    }
}
